package com.jet.chat.command;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;
import com.jet.chat.service.ChatMessage;
import com.jet.chat.service.ChatMessageService;



public class ChatCommandWhisper implements ChatCommand {

	@Override
	public void execute(ChatServer chatServer, ChatSession chatSession, ChatMessage chatMessage) {
		Pattern pattern = Pattern.compile("^/\\w+\\s(\\w+)\\s(.*)$");
		Matcher matcher = pattern.matcher(chatMessage.getMessage());
		if (!matcher.matches()) {
			ChatMessageService.send(new ChatMessage("invalid command format"), chatSession.getWriter());
		} else {
			String recieverUsername = matcher.group(1);
			String content = chatSession.getUsername() + " whispers: " + matcher.group(2);
			ChatSession recieverSession = chatServer.getChannel(chatSession.getChannelName()).getSession(recieverUsername);
			if (recieverSession == null ) {
				ChatMessageService.send(new ChatMessage("server > no such reciever online"), chatSession.getWriter());
			} else {
				chatServer.getDbService().addHistory(chatSession.getId(), recieverSession.getId(), chatSession.getChannelName(), matcher.group(2));
				ChatMessageService.send(new ChatMessage(content), recieverSession.getWriter());
			}
		}
	}

}
